package socket.netty;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * Created by zhourui on 2016/9/2.
 */
public class TcpClient {
    public static final String IP_ADDR = "localhost";//服务器地址
    public static final int PORT = 12345;//服务器端口号
    public static void main(String[] args) throws IOException, InterruptedException {
        Socket socket = null;
        OutputStream out = null;
        InputStream in = null;

        try{
            socket = new Socket(IP_ADDR, PORT);
            out = socket.getOutputStream();
            in = socket.getInputStream();

            // 请求服务器
            out.write("第一次请求".getBytes("UTF-8"));
            out.flush();

            // 获取服务器响应，输出
            byte[] byteArray = new byte[1024];
            int length = in.read(byteArray);
            System.out.println(new String(byteArray, 0, length, "UTF-8"));

            Thread.sleep(5000);

            // 再次请求服务器
            out.write("第二次请求".getBytes("UTF-8"));
            out.flush();

            // 再次获取服务器响应，输出
            byteArray = new byte[1024];
            length = in.read(byteArray);
            System.out.println(new String(byteArray, 0, length, "UTF-8"));

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭连接
            in.close();
            out.close();
            socket.close();
        }
    }
}